<template>
  <el-row>
    <el-card>
      <el-button-group>
        <el-button
          v-for="(item, index) in $t('financeModule.list.status1')"
          :key="index"
          :type="chType === item['value'] ? 'primary' : ''"
          @click="changeStatus(item['value'])"
        >
          {{ item['desc'] }}
        </el-button>
      </el-button-group>
      <el-divider />
      <el-form ref="searchForm" :inline="true" :model="searchForm">
        <el-form-item :label="$t('financeModule.list.createDate')">
          <el-date-picker
            v-model="time"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.reviewDate')">
          <el-date-picker
            v-model="reviewTime"
            type="daterange"
            range-separator="~"
            :start-placeholder="$t('common.startDate')"
            :end-placeholder="$t('common.endDate')"
          />
        </el-form-item>
        <el-form-item :label="$t('financeModule.list.productType')">
          <el-select v-model="searchForm.productType" clearable :placeholder="$t('financeModule.list.loanType')">
            <el-option
              v-for="item in $t('financeModule.list.orderTypeList')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="chType !== 3" :label="$t('financeModule.list.paymentStatus')">
          <el-select v-model="searchForm.status" clearable>
            <el-option
              v-for="item in $t('financeModule.list.state')"
              :key="item.value"
              :label="item.desc"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input v-model="inputData" :placeholder="$t('common.input')" class="input-with-select">
            <el-select slot="prepend" v-model="selectData">
              <el-option
                v-for="(item, index) in $t('financeModule.list.search')"
                :key="index"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-input>
        </el-form-item>
        <el-row>
          <el-button type="primary" @click="search">
            {{ $t('common.search') }}
          </el-button>
          <el-button @click="reset">
            {{ $t('common.reset') }}
          </el-button>
          <el-button :disabled="!(totalNumber > 0)" @click="exportList">
            {{ $t('common.ex') }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>
    <el-card>
      <el-table
        v-loading="loading"
        :header-cell-style="{background:'#eef1f6',color:'#606266'}"
        :data="tableData"
        border
        :stripe="true"
        style="width: 100%;"
      >
        <el-table-column
          fixed="left"
          prop="orderNo"
          :label="tableText['orderNo']"
          min-width="170"
        />
        <el-table-column
          prop="createTimeStr"
          :label="tableText['createTime']"
          min-width="170"
        />
        <el-table-column
          prop="phoneNumber"
          :label="tableText['userNo']"
          min-width="150"
        />
        <el-table-column
          prop="userName"
          :label="tableText['userName']"
          min-width="120"
        />
        <el-table-column
          prop="productType"
          :label="tableText['type']"
          min-width="200"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row['productType'], 'orderTypeList') }}
          </template>
        </el-table-column>
        <el-table-column
          prop="auditPassTimeStr"
          :label="$t('financeModule.list.reviewDate')"
          min-width="170"
        />
        <el-table-column
          prop="applyCash"
          :label="tableText['loanMoney']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['applyCash'] ? scope.row['applyCash'].toFixed(2) : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="loanDays"
          :label="tableText['limit']"
          min-width="150"
        />
        <el-table-column
          prop="payMoney"
          :label="tableText['loanAmount']"
          min-width="150"
        >
          <template slot-scope="scope">
            {{ scope.row['payMoney'] ? scope.row['payMoney'].toFixed(2) : 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="operation"
          :label="tableText['operateResult']"
          min-width="120"
        />
        <el-table-column
          prop="payDate"
          :label="tableText['operateTime']"
          min-width="170"
        />
        <el-table-column
          prop="operateName"
          :label="tableText['operateName']"
          min-width="120"
        />
        <el-table-column
          fixed="right"
          prop="status"
          :label="tableText['orderStatus']"
          min-width="170"
        >
          <template slot-scope="scope">
            {{ setValue(scope.row['status'], 'state') }}
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          :label="$t('common.operate.name')"
          min-width="300"
        >
          <template slot-scope="scope">
            <el-button v-if="scope.row['status'] === 3" size="small" @click="review(scope.row)">{{ $t('common.btnGroup.f') }}</el-button>
            <el-button size="small" @click="loan(scope.row)">{{ $t('financeModule.list.makeLoan') }}</el-button>
            <el-button size="small" @click="toDetail(scope.row)">{{ $t('common.btnGroup.a') }}</el-button>
          </template>
        </el-table-column>

      </el-table>
      <div class="block">
        <el-pagination
          :current-page="searchForm.currentPage"
          :page-sizes="[10, 20, 30, 40, 50]"
          :page-size="searchForm.pageSize"
          :total="totalNumber"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <loan-list-dialog
      :show-dialog="editDialog"
      :choose-item="chooseItem"
      @change-dialog="changeDialog"
      @edit-success="editSuccess"
    />
    <loan-review-dialog
      :show-dialog="reviewDialog"
      :choose-item="chooseReviewItem"
      @change-dialog="changeReviewDialog"
      @edit-success="editSuccess"
    />
  </el-row>
</template>

<script>
import { queryPayment, queryRepaymentManageExport } from '@/api/finance'
import { formatDate, ObjToQueryString } from '@/utils/method'
import LoanListDialog from '@/components/finance/loan-list-dialog'
import LoanReviewDialog from '@/components/finance/loan-review-dialog'
export default {
  name: 'LoanList',
  components: {
    LoanListDialog,
    LoanReviewDialog
  },
  data() {
    return {
      loading: true,
      editDialog: false,
      reviewDialog: false,
      chType: 1,
      time: null,
      reviewTime: [new Date((new Date()).getTime() - 1000 * 60 * 60 * 24 * 6), new Date()],
      tableData: [],
      tableText: {},
      totalNumber: 0,
      searchForm: this.params(),
      inputData: null,
      selectData: 'orderNo',
      chooseItem: {
        orderId: null,
        balanceApplyId: null,
        paymentResult: null,
        paymentChannel: null,
        ourAccount: null,
        serialNumber: null,
        payDate: null,
        payMoney: null,
        option: null
      },
      chooseReviewItem: {
        orderId: null,
        userId: null,
        type: null,
        option: null
      }
    }
  },
  mounted() {
    this.tableText = this.$t('financeModule.list.detail')
    this.getData()
  },
  methods: {
    search() {
      this.searchForm.currentPage = 1
      this.getData()
    },
    params() {
      return {
        currentPage: 1,
        pageSize: 10,
        createTimeStart: null,
        createTimeEnd: null,
        auditTimeStart: null,
        auditTimeEnd: null,
        productType: '',
        status: '',
        orderNo: null,
        phoneNumber: null,
        userName: null
      }
    },
    reset() {
      this.searchForm = this.params()
      this.selectData = 'orderNo'
      this.inputData = null
      this.time = null
      this.reviewTime = [new Date((new Date()).getTime() - 1000 * 60 * 60 * 24 * 6), new Date()]
      this.getData()
    },
    changeStatus(type) {
      this.chType = type
      this.searchModel.status = type === 3 ? type : null
      this.getData()
    },
    getData() {
      this.loading = true
      const data = this.searchData()
      queryPayment(data)
        .then(res => {
          this.loading = false
          if (res.success) {
            this.tableData = res.data
            this.totalNumber = res.page ? res.page['totalNumber'] : 0
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(err => {
          this.$message.error(err.message)
        })
    },
    exportList() {
      queryRepaymentManageExport(this.searchData())
    },
    searchData() {
      const data = {
        currentPage: this.searchForm.currentPage,
        pageSize: this.searchForm.pageSize,
        productType: this.searchForm.productType,
        paymentStatus: this.searchForm.paymentStatus,
        endStatus: this.searchForm.endStatus,
        id: this.searchForm.id
      }
      if (this.time && this.time.length > 1) {
        data['createTimeStart'] = formatDate(new Date(this.time[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['createTimeEnd'] = formatDate(new Date(this.time[1]), 'yyyy-MM-dd') + ' 23:59:59'
      }
      if (this.planRepaymentTime && this.planRepaymentTime.length > 1) {
        data['planRepaymentTimeStart'] = formatDate(new Date(this.planRepaymentTime[0]), 'yyyy-MM-dd') + ' 00:00:00'
        data['planRepaymentTimeEnd'] = formatDate(new Date(this.planRepaymentTime[1]), 'yyyy-MM-dd') + ' 23:59:59'
      }
      if (this.selectData && this.inputData) {
        data[this.selectData] = this.inputData
      }
      return data
    },
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.searchForm.currentPage = val
      this.getData()
    },
    toDetail(item) {
      const paramData = {
        orderId: item['orderId'],
        userId: item['userId']
      }
      const para = ObjToQueryString(paramData)
      window.open(`${window.location.origin + window.location.pathname}#/order/detail?${para}`, '_blank')
    },
    setValue(val, data) {
      const map = this.$t(`financeModule.list.${data}`)
      const name = map.filter(v => {
        return v['value'] === val
      })
      return name && name[0] && name[0]['desc'] ? name[0]['desc'] : ''
    },
    choose(param) {
      this.chooseItem.orderId = param.orderId
      this.chooseItem.balanceApplyId = param.balanceApplyId
      this.chooseItem.paymentResult = param.paymentResult
      this.chooseItem.paymentChannel = param.paymentChannel
      this.chooseItem.ourAccount = param.ourAccount
      this.chooseItem.serialNumber = param.serialNumber
      this.chooseItem.payDate = param.payDate
      this.chooseItem.payMoney = param.payMoney
      this.chooseItem.option = param.option
    },
    chooseReview(item) {
      this.chooseReviewItem.orderId = item.orderId
      this.chooseReviewItem.userId = item.userId
      this.chooseReviewItem.type = item.type
      this.chooseReviewItem.option = item.option
    },
    changeDialog(param) {
      this.editDialog = param
      setTimeout(() => {
        this.choose({})
      }, 10)
    },
    editSuccess() {
      this.getData()
    },
    loan(item) {
      this.choose({
        orderId: item['orderId'],
        payMoney: item['payMoney'],
        balanceApplyId: item['id'],
        paymentResult: 1
      })
      this.editDialog = true
    },
    changeReviewDialog(param) {
      this.reviewDialog = param
      setTimeout(() => {
        this.chooseReview({})
      }, 10)
    },
    review(item) {
      this.chooseReview({
        orderId: item['orderId'],
        userId: item['userId'],
        option: item['option']
      })
      this.reviewDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card{
  margin: 10px;
}
</style>
